import typing as T
import json
import logging

from ...mapper._ChatHistoryCacheMapper import _chatHistoryCacheMapper
from ._UserChatHistoryService import _UserChatHistoryService
from ....common.constant.chat import RoleType
from ....init.Global import configuration
from ....pojo.entity.UserChatHistory import UserChatHistory


class _ChatHistoryCacheService:

    @classmethod
    async def getHistory(cls, sessionId: int, limit: int = 10):
        if await _chatHistoryCacheMapper.exists(sessionId):
            result = await _UserChatHistoryService.getBySessionId(sessionId, limit)
            logging.info(f"从数据库查找到:{result[::-1]}")
            await cls.setHistory(
                sessionId,
                result,
            )
        return await _chatHistoryCacheMapper.getCacheBySessionId(sessionId, limit)

    @classmethod
    async def addHistory(
        cls, sessionId: int, history: list[list[str]], ttl=60 * 60 * 2
    ):
        await _chatHistoryCacheMapper.addCacheBySessionId(sessionId, history, ttl)
        await cls.validate(sessionId)

    @classmethod
    async def validate(cls, sessionId: int):
        """
        判断是否要弹出缓存
        并插入到数据库
        """
        length = await _chatHistoryCacheMapper.getCacheLengthBySessionId(sessionId)
        max_cache = configuration.max_cache

        if length < max_cache:
            return

        logging.info(f"缓存长度{length}达到或超过最大长度{max_cache}....准备弹出")
        max_history = configuration.max_history
        deleteCount = length - max_history
        result = await _chatHistoryCacheMapper.deleteCacheBySessionId(
            sessionId, deleteCount
        )
        persisted = int(result[1].decode())
        result = [json.loads(msg.decode()) for msg in result[0]]
        if persisted >= len(result):
            logging.info(f"弹出{len(result)}条缓存")
            await _chatHistoryCacheMapper.setPersisted(
                sessionId, persisted - len(result)
            )
            return
        count = len(result) - persisted
        data = []
        for message in result[-count:]:
            data.append(
                UserChatHistory(
                    sessionId=sessionId,
                    content=json.dumps(message[1], ensure_ascii=False),
                    isAi=message[0] == RoleType.AI,
                )
            )
        await _UserChatHistoryService.insertBatch(data)
        logging.info(f"弹出{len(result)}条缓存，其中{count}条缓存插入到数据库")

    @classmethod
    async def setHistory(
        cls, sessionId: int, history: list[list[str]], ttl=60 * 60 * 2
    ):
        await _chatHistoryCacheMapper.setCacheBySessionId(sessionId, history, ttl)
